package com.ruoyi.business.service.impl;

import com.ruoyi.business.domain.Business;
import com.ruoyi.business.domain.BusinessMoney;
import com.ruoyi.business.mapper.BusinessMapper;
import com.ruoyi.business.service.BusinessService;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.SysDictDataService;
import com.ruoyi.system.service.SysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 基础业务Service业务层处理
 * 
 * @author xx
 * @date 2020-03-16
 */
@Service
public class BusinessServiceImpl implements BusinessService {
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDictDataService sysDictDataService;

    /**
     * 查询基础业务
     * 
     * @param id 基础业务ID
     * @return 基础业务
     */
    @Override
    public Business selectBusinessById(Long id) {
        return businessMapper.selectBusinessById(id);
    }

    /**
     * 查询基础业务列表
     * 
     * @param business 基础业务
     * @return 基础业务
     */
    @Override
    public List<Business> selectBusinessList(Business business) {
        if (business.getUserId() != null) {
            SysUser sysUser = new SysUser();
            sysUser.setPid(business.getUserId());
            business.setUserIds(sysUserService.selectUserList(sysUser).stream().map(SysUser::getUserId).collect(Collectors.toList()));
        }
        return businessMapper.selectBusinessList(business);
    }

    /**
     * 新增基础业务
     * 
     * @param business 基础业务
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public int insertBusiness(Business business) {
        SysUser user = BeanUtils.copyBean(SecurityUtils.getSubject().getPrincipal(), SysUser.class);
        business.setCreateBy(user.getLoginName());
        business.setCreateTime(DateUtils.getNowDate());
        List<BusinessMoney> prices = business.getPrices();
        // 非管理员账号添加业务校验价格，不能低于上级代理商的
        if (!SysUser.isAdmin(user.getUserId())) {
            Business pBusiness = selectBusinessByUserId(business.getBusinessType(), business.getRechargeChannel(), user.getUserId());
            if (Objects.isNull(pBusiness)) {
                throw new BusinessException("所属用户选择异常");
            }

            Map<String, Double> collect = pBusiness.getPrices().parallelStream().collect(Collectors.toMap(BusinessMoney::getValue, BusinessMoney::getMoney));
            prices.forEach(businessMoney -> {
                if (businessMoney.getMoney() < collect.get(businessMoney.getValue())) {
                    throw new BusinessException("业务价格有误，" + businessMoney.getLabel() + "不能低于自身的" + collect.get(businessMoney.getValue()));
                }
            });
        }
        int count = businessMapper.insertBusiness(business);
        if (CollectionUtils.isNotEmpty(prices)) {
            // sd_business_type的备注必须要填写对应价格的字典名称dict_type.
            String type = sysDictDataService.selectDictDataByType("sd_business_type").stream().filter(sysDictData -> StringUtils.equals(business.getBusinessType().toString(), sysDictData.getDictValue())).map(SysDictData::getRemark).findAny().orElse("");
            prices.forEach(price -> {
                price.setBusinessId(business.getId());
                price.setBusinessType(business.getBusinessType());
                price.setType(type);
            });
            businessMapper.insertBusinessMoneys(prices);
        }
        return count;
    }

    /**
     * 修改基础业务
     * 
     * @param business 基础业务
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public int updateBusiness(Business business) {
        SysUser user = BeanUtils.copyBean(SecurityUtils.getSubject().getPrincipal(), SysUser.class);
        business.setUpdateBy(user.getLoginName());
        if (!SysUser.isAdmin(user.getUserId())) {
            Business pBusiness = selectBusinessByUserId(business.getBusinessType(), business.getRechargeChannel(), user.getUserId());
            if (Objects.isNull(pBusiness)) {
                throw new BusinessException("所属用户选择异常");
            }

            Map<String, Double> collect = pBusiness.getPrices().parallelStream().collect(Collectors.toMap(BusinessMoney::getValue, BusinessMoney::getMoney));
            business.getPrices().forEach(businessMoney -> {
                if (businessMoney.getMoney() < collect.get(businessMoney.getValue())) {
                    throw new BusinessException("业务价格有误，" + businessMoney.getLabel() + "不能低于自身的" + collect.get(businessMoney.getValue()));
                }
            });
            if (Objects.equals(user.getUserId(), business.getUserId())) {
                throw new BusinessException("不能修改自身信息，请联系上级代理商或者管理员");
            }
        }
        business.setUpdateTime(DateUtils.getNowDate());
        List<BusinessMoney> prices = business.getPrices();
        if (CollectionUtils.isNotEmpty(prices)) {
            String type = sysDictDataService.selectDictDataByType("sd_business_type").stream().filter(sysDictData -> StringUtils.equals(business.getBusinessType().toString(), sysDictData.getDictValue())).map(SysDictData::getRemark).findAny().orElse("");
            businessMapper.deleteBusinessMoneys(business.getId());
            prices.forEach(price -> {
                price.setBusinessId(business.getId());
                price.setBusinessType(business.getBusinessType());
                price.setType(type);
            });
            businessMapper.insertBusinessMoneys(prices);
        }
        return businessMapper.updateBusiness(business);
    }

    /**
     * 删除基础业务对象
     * 
     * @param business 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteBusinessByIds(Business business) {
        business.setIdList(Arrays.asList(Convert.toLongArray(business.getIds())));
        int result = businessMapper.deleteBusinessByIds(business);
        for (Long id : business.getIdList()) {
            businessMapper.deleteBusinessMoneys(id);
        }
        return result;
    }

    /**
     * 删除基础业务信息
     * 
     * @param id 基础业务ID
     * @return 结果
     */
    @Override
    public int deleteBusinessById(Long id) {
        return businessMapper.deleteBusinessById(id);
    }

    @Override
    public int changeStatus(Business business) {
        return businessMapper.changeStatus(business);
    }

    @Override
    public int checkBusinessCodeUnique(String businessCode) {
        return businessMapper.checkBusinessCodeUnique(businessCode);
    }

    @Override
    public Business selectBusinessByUserId(Integer businessType, Integer rechargeChannel, Long userId) {
        return businessMapper.selectBusinessByUserId(businessType, rechargeChannel, userId);
    }

    @Override
    public List<Integer> selectBusinessTypesByUserId(Long userId) {
        return businessMapper.selectBusinessTypesByUserId(userId);
    }

    @Override
    public List<Integer> selectRechargeChannelsByUserId(Long userId) {
        return businessMapper.selectRechargeChannelsByUserId(userId);
    }

}
